//#define OFFLINE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Xeml.Document;
using System.IO;
using Xeml.Document.Contracts;
using Xid.Controls;
using XemlUtilities.Indexing;
using SplashScreen;
using Mpi.Common.Collections;
using Mpi.Common.Controls;
using ComponentFactory.Krypton.Toolkit;
using System.Threading;
using System.Diagnostics;
using System.Linq;
using Xeml.Document.XemlEventArgs;
using Xeml.Sampling.Contracts;
using XemlUtilities.DataSet;
using Xeml.Document.CoreObjects;

namespace XemlInteractiveDesigner
{
    public partial class MainForm : KryptonForm
    {
        private BackgroundWorker _showBusyWorker;
        private BackgroundWorker _showSplashWorker;
        private int lastDetailContainerHeight;
        private int lastParameterContainerWidth;
        private FileManager fMgr;
        private StoryEditForm sef;
        private AnnotationForm af;
        private BusyDialog _busyDialog;
        private SplashForm _splashForm;

        private ToolStripDateTimePicker _toolStripDateTimePickerStartTime;
        private ToolStripTimeSpanBox _toolStripTimeBoxSplitTime;
        private ToolStripTimeSpanBox _toolStripTimeBoxObPoint;
        private ToolStripTimeSpanBox _toolStripTimeBoxEvent;
        private ToolStripTimeSpanBox _toolStripTimeBoxObservationLength;

        List<ToolStripItem> expItems = new List<ToolStripItem>();
        List<ToolStripItem> storyItems = new List<ToolStripItem>();
        List<ToolStripItem> splitItems = new List<ToolStripItem>();
        List<ToolStripItem> obPointItems = new List<ToolStripItem>();
        List<ToolStripItem> eventItems = new List<ToolStripItem>();

        System.Windows.Forms.Timer MemoryTicker;

        private bool _started = false;
        public MainForm()
        {
            File.Delete(Path.Combine(Application.StartupPath, "debug.txt"));
            Debug.Listeners.Add(new TextWriterTraceListener(Path.Combine(Application.StartupPath, "debug.txt")));
            Debug.WriteLine(string.Format("user config is going to '{0}'", System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath));

#if OFFLINE
            MessageBox.Show("This is a specialised version for the review process. We have tried to eliminate all " +
                " usage of online resources from our webserver. However, for the help functionality about parameters still the wiki from our webserver is needed." +
                " But you will get an extra warning and you can decide whether or not the call will be proceeded.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
#endif

            // Instantiate some single tons classes so we can hook them up with the right events
            Xeml.Document.Manager.OnlineCacheManager.Instance.MessageEmitted += OnMessageEmitted;
            Xeml.SQLDataProviders.DataProviderManager.Instance.MessageEmitted += OnMessageEmitted;
            //Xeml.Manager.OntologyManager.Instance.MessageEmitted += OnMessageEmitted;

            InitWorker();
            _showSplashWorker.RunWorkerAsync();

            //System.Net.WebRequest wr = System.Net.WebRequest.Create("http://xeml/EnvOntologyRecent");
            ////OperatingSystem os = Environment.OSVersion;
            //System.Net.WebResponse wres = wr.GetResponse();

            sef = new StoryEditForm();
            af = new AnnotationForm();

            InitializeComponent();
            #region Build ToolStrip
            this.storyItems.Add(toolStripSeparatorStory);
            this.storyItems.Add(toolStripLabelStoryLogo);
            this.storyItems.Add(toolStripTextBoxStoryLabel);
            this.storyItems.Add(toolStripButtonStoryAnnotations);


            _toolStripTimeBoxObservationLength = new ToolStripTimeSpanBox();
            _toolStripTimeBoxObservationLength.AutoToolTip = true;
            _toolStripTimeBoxObservationLength.ToolTipText = "Estimated experiment duration";
            toolStripDetails.Items.Insert(5, _toolStripTimeBoxObservationLength);


            _toolStripDateTimePickerStartTime = new ToolStripDateTimePicker();
            _toolStripDateTimePickerStartTime.Width = 150;
            _toolStripDateTimePickerStartTime.AutoToolTip = true;
            _toolStripDateTimePickerStartTime.ToolTipText = "Experiments start date";
            toolStripDetails.Items.Insert(7, _toolStripDateTimePickerStartTime);

            _toolStripTimeBoxSplitTime = new ToolStripTimeSpanBox();
            _toolStripTimeBoxSplitTime.AutoToolTip = true;
            _toolStripTimeBoxSplitTime.ToolTipText = "Split time";
            toolStripDetails.Items.Insert(12, _toolStripTimeBoxSplitTime);


            _toolStripTimeBoxObPoint = new ToolStripTimeSpanBox();
            _toolStripTimeBoxObPoint.AutoToolTip = true;
            _toolStripTimeBoxObPoint.ToolTipText = "Time";
            toolStripDetails.Items.Insert(19, _toolStripTimeBoxObPoint);

            _toolStripTimeBoxEvent = new ToolStripTimeSpanBox();
            _toolStripTimeBoxEvent.AutoToolTip = true;
            _toolStripTimeBoxEvent.ToolTipText = "Time";
            toolStripDetails.Items.Insert(26, _toolStripTimeBoxEvent);

            //Story group
            this.expItems.Add(_toolStripTimeBoxObservationLength);
            this.expItems.Add(toolStripTextBoxExpName);
            this.expItems.Add(_toolStripDateTimePickerStartTime);
            this.expItems.Add(toolStripLabelExpName);
            this.expItems.Add(toolStripLabelStartDate);
            this.expItems.Add(toolStripSeparatorExperiment);
            this.expItems.Add(toolStripLabelExpLogo);
            this.expItems.Add(toolStripLabelObservationLength);

            //Story group
            this.storyItems.Add(toolStripSeparatorStory);
            this.storyItems.Add(toolStripLabelStoryLogo);
            this.storyItems.Add(toolStripTextBoxStoryLabel);
            this.storyItems.Add(toolStripButtonStoryAnnotations);
            this.storyItems.Add(toolStripLabelStoryLabel);

            //Split group
            this.splitItems.Add(toolStripSeparatorStory);
            this.splitItems.Add(toolStripLabelSplitLogo);
            this.splitItems.Add(toolStripTextBoxStoryLabel);
            this.splitItems.Add(toolStripButtonStoryAnnotations);
            this.splitItems.Add(_toolStripTimeBoxSplitTime);
            this.splitItems.Add(toolStripLabelTimeEditor);
            this.splitItems.Add(toolStripLabelStoryLabel);
            this.splitItems.Add(toolStripLabelSplitTime);

            //ObPoint group
            this.obPointItems.Add(toolStripSeparatorObservationPoint);
            this.obPointItems.Add(toolStripLabelObPointLogo);
            this.obPointItems.Add(_toolStripTimeBoxObPoint);
            this.obPointItems.Add(toolStripButtonViewSamples);
            this.obPointItems.Add(toolStripButtonDeleteSamples);
            this.obPointItems.Add(toolStripButtonObPointAnnotations);
            this.obPointItems.Add(toolStripLabelTimeEditor);
            this.obPointItems.Add(toolStripLabelObPointTime);


            //Event group
            this.eventItems.Add(toolStripSeparatorEvent);
            this.eventItems.Add(toolStripLabelEventLogo);
            this.eventItems.Add(toolStripTextBoxEventLabel);
            this.eventItems.Add(_toolStripTimeBoxEvent);
            this.eventItems.Add(toolStripButtonEventAnnotations);
            this.eventItems.Add(toolStripLabelTimeEditor);
            this.eventItems.Add(toolStripLabelEventTime);
            this.eventItems.Add(toolStripLabelEventLabel);


            //if (os.Version < new Version(6, 0))
            //{
            //    kryptonManager.GlobalAllowFormChrome = true;
            //    kryptonPalette1.AllowFormChrome = InheritBool.True;
            //    kryptonPalette2.AllowFormChrome = InheritBool.True;
            //}
            ToolStripManager.Merge(xemlViewer.toolStripEditActions, toolStripStoryBoard);
            ToolStripManager.Merge(contextMenuStrip1, xemlViewer.ContextMenuStrip);
            #endregion
            /// xemlViewer.ContextMenu.MergeMenu(testToolStripMenuItem);
            //xemlViewer.ContextMenu.MergeMenu(contextMenuStrip1);

            ApplyStyle();

            fMgr = new FileManager();

            fMgr.FileLoaded += new EventHandler(OnDocumentLoaded);
            fMgr.FileLoaded += new EventHandler(OnNewFile);
            fMgr.FilePathChanged += new EventHandler(fMgr_FilePathChanged);
            fMgr.SomethingChanged += new EventHandler(fMgr_SomethingChanged);
            fMgr.FileSaved += new EventHandler(fMgr_FileSaved);
            fMgr.FilePathNeeded += new EventHandler<FilePathNeededEventArgs>(fMgr_FilePathNeeded);
            //fMgr.EditModeChanged    += new EventHandler(fMgr_EditModeChanged);
            fMgr.DesignModeRejected += new EventHandler(fMgr_DesignModeRejected);
            fMgr.LogChanged += new EventHandler(fMgr_LogChanged);
            fMgr.UndoAvailabilityChanged += new EventHandler<UndoRedoAvailabilityEventArgs>(fMgr_UndoAvailabilityChanged);
            fMgr.RedoAvailabilityChanged += new EventHandler<UndoRedoAvailabilityEventArgs>(fMgr_RedoAvailabilityChanged);

            //  SetupSyntaxDoc();

            //kryptonHeaderGroupDetails.ButtonSpecs[0].Click      += new EventHandler(CollapsDetailContainer);
            kryptonHeaderGroupParameter.ButtonSpecs[0].Click += new EventHandler(CollapseParameterContainer);

            validationLogBindingSource.DataSource = fMgr.ValidationLog;
            OnLogFilterChange(null, null);
            //this.xemlViewer.ObservationPointSelected += new EventHandler(XemlViewer_ObservationPointSelected);
            //this.xemlViewer.ExperimentSelected += new EventHandler(XemlViewer_ExperimentSelected);
            //this.xemlViewer.StorySelected += new EventHandler(XemlViewer_StorySelected);
            //this.xemlViewer.EventSelected += new EventHandler(XemlViewer_EventSelected);

            this.xemlViewer.ObjectSelectionChanged += new EventHandler<Xeml.Visualization.SelectedElementChangedEventArgs>(XemlViewer_ObjectSelectionChanged);

            this.germPlasmPoolsMgrCtrl1.IndividualsPoolCountChanged += new EventHandler(germPlasmPoolsMgrCtrl1_IndividualsPoolCountChanged);
            this.xemlViewer.TimeEditPreviewChange += new EventHandler<Mpi.Common.PropertyHasChangedEventArgs<TimeSpan>>(xemlViewer_TimeEditPreviewChange);

            parameterTreeCtrl1.SelectedParamTreeNodeChanged += new EventHandler(OnParameterNavigation);
            parameterTreeCtrl1.ParameterPopulated += new EventHandler(parameterTreeCtrl1_ParameterPopulated);
            parameterTreeCtrl1.ParameterDePopulated += new EventHandler(parameterTreeCtrl1_ParameterPopulated);

            //fMgr.New();
            //sf.Close();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            fMgr.New();
            EndSplashScreen();
            _started = true;
            _showBusyWorker.RunWorkerAsync();

            fMgr.BackgroundWorkStarted += new EventHandler<BusyEventArgs>(OnStartBusyDialog);
            fMgr.BackgroundWorkEnded += new EventHandler(OnEndBusyDialog);
            htmlReportCtrl1.BackgroundWorkStarted += new EventHandler<BusyEventArgs>(OnStartBusyDialog);
            htmlReportCtrl1.BackgroundWorkEnded += new EventHandler(OnEndBusyDialog);
            tableFormatterCtrl1.BackgroundWorkStarted += new EventHandler<BusyEventArgs>(OnStartBusyDialog);
            tableFormatterCtrl1.BackgroundWorkEnded += new EventHandler(OnEndBusyDialog);
            this.TopLevel = true;
            this.Activate();
#if !DEBUG
            MessageBox.Show(
                @"Be aware this is technical preview of the next verion of XEML Interactive Designer.
If you open documents generated by a previous version of XiD they get automatically converted.
If you save the document in the new format version they are not longer readable by older verions of XiD.", "Important Notice", MessageBoxButtons.OK, MessageBoxIcon.Warning);
#else
            MemoryTicker = new System.Windows.Forms.Timer();
            MemoryTicker.Interval = 2000;
            MemoryTicker.Tick += new EventHandler((object sender1, EventArgs e1) =>
            {
                if (!this.Disposing && !this.IsDisposed && MemoryTicker.Enabled)
                {
                    this.Invoke(new MethodInvoker(delegate { toolStripStatusLabelEditMode.Text = string.Format("memory usage: {0:#,### kB}", Math.Round(Process.GetCurrentProcess().PrivateMemorySize64 / 1024D)); }));
                }
            });
            MemoryTicker.Start();
#endif
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            //jahu();
        }

        private void InitWorker()
        {
            _showBusyWorker = new BackgroundWorker();
            _showBusyWorker.WorkerSupportsCancellation = true;
            _showBusyWorker.DoWork += new DoWorkEventHandler(_showBusyWorker_DoWork);

            _showSplashWorker = new BackgroundWorker();
            _showSplashWorker.DoWork += new DoWorkEventHandler(_showSplashWorker_DoWork);
        }
        private IBusyReporter _currentBusyReporter;
        private void OnStartBusyDialog(object sender, BusyEventArgs e)
        {
            if (_started && _currentBusyReporter == null)
            {
                // Kenny: I disabled this loading dialog as it stays on top even when the program errrs on something.
                //_currentBusyReporter = sender as IBusyReporter;
                //_busyDialog.Invoke(new MethodInvoker(delegate()
                //{
                //    _busyDialog.ShowBusy(this, e.Message);
                //}));
                this.Enabled = false;
            }
        }
        private void OnEndBusyDialog(object sender, EventArgs e)
        {
            //if (_busyDialog != null && sender == _currentBusyReporter)
            //{
            this.Enabled = true;
            //_busyDialog.Invoke(new MethodInvoker(delegate()
            //{
            //    _busyDialog.HideBusy();
            //}
            //    ));
            //_currentBusyReporter = null;
            //}
        }

        private void EndSplashScreen()
        {
            if (_splashForm != null)
            {
                _splashForm.Invoke(new MethodInvoker(delegate() { _splashForm.Close(); }));
                _splashForm = null;
            }
        }
        private void _showSplashWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Application.EnableVisualStyles();
            _splashForm = new SplashForm();
            _splashForm.StartPosition = FormStartPosition.CenterScreen;
            Application.Run(_splashForm);
        }
        private void _showBusyWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            _busyDialog = new BusyDialog();
            _busyDialog.Message = (e.Argument as string) + "\r\nPlease wait...";

            _busyDialog.StartPosition = FormStartPosition.Manual;

            _busyDialog.DesktopLocation = new Point(-100, -100); ;
            _busyDialog.Size = new Size(1, 1);
            Application.Run(_busyDialog);
        }

        void OnParameterNavigation(object sender, EventArgs e)
        {
            parameterEditCtrl1.NavigateTo(xemlViewer.SelectedStoryBase.Content, parameterTreeCtrl1.SelectedNode.VariableSupervisor, parameterTreeCtrl1.SelectedNode.VariableSupervisor.TermId);
            xemlViewer.SelectedTerm = parameterTreeCtrl1.SelectedNode.VariableSupervisor.SupervisedObjects.FirstOrDefault();
        }

        void parameterTreeCtrl1_ParameterPopulated(object sender, EventArgs e)
        {
            xemlViewer.SelectedTerm = parameterTreeCtrl1.SelectedVariableNode.VariableSupervisor.SupervisedObjects.FirstOrDefault();
        }

        void xemlViewer_TimeEditPreviewChange(object sender, Mpi.Common.PropertyHasChangedEventArgs<TimeSpan> e)
        {
            toolStripLabelTimeEditor.Text = e.NewValue.ToString();
        }

        void fMgr_RedoAvailabilityChanged(object sender, UndoRedoAvailabilityEventArgs e)
        {
            toolStripButtonRedo.Enabled = e.Available;
            redoToolStripMenuItem.Enabled = e.Available;
        }

        void fMgr_UndoAvailabilityChanged(object sender, UndoRedoAvailabilityEventArgs e)
        {
            toolStripButtonUndo.Enabled = e.Available;
            undoToolStripMenuItem.Enabled = e.Available;

        }

        void germPlasmPoolsMgrCtrl1_IndividualsPoolCountChanged(object sender, EventArgs e)
        {
            if (germPlasmPoolsMgrCtrl1.Story.Pools.Count > 0)
                kryptonPageGermPlasm.Text = "Genotypes" + "(" + germPlasmPoolsMgrCtrl1.Story.Pools.Count + ")";
            else
                kryptonPageGermPlasm.Text = "Genotypes";
        }

        private void UnHideGroup(List<ToolStripItem> group, bool hide)
        {
            foreach (ToolStripItem tsi in group)
            {
                tsi.Visible = hide;
            }
        }

        void XemlViewer_ObjectSelectionChanged(object sender, Xeml.Visualization.SelectedElementChangedEventArgs e)
        {
            toolStripDetails.SuspendLayout();
            UnHideGroup(expItems, false);
            UnHideGroup(storyItems, false);
            UnHideGroup(splitItems, false);
            UnHideGroup(obPointItems, false);
            UnHideGroup(eventItems, false);
            if (e.SelectedStoryChanged || e.MostTopSelectedElement == Xeml.Visualization.VisualDocElement.Story || e.MostTopSelectedElement == Xeml.Visualization.VisualDocElement.SplitDot)
            {
                if (xemlViewer.SelectedStoryBase != null)
                {
                    if (e.MostTopSelectedElement == Xeml.Visualization.VisualDocElement.Story || e.MostTopSelectedElement == Xeml.Visualization.VisualDocElement.SplitDot)
                    {
                        //   xemlObjectDetailsCtrl.SetObject(xemlViewer.SelectedStoryBase.Content);
                        if (xemlViewer.SelectedStoryBase.Content is Story)
                        {
                            UnHideGroup(storyItems, true);
                            toolStripTextBoxStoryLabel.TextBox.DataBindings.Clear();
                            toolStripTextBoxStoryLabel.TextBox.DataBindings.Add("Text", xemlViewer.SelectedStoryBase.Content, "Label", true, DataSourceUpdateMode.OnPropertyChanged);
                            toolStripButtonStoryAnnotations.Tag = xemlViewer.SelectedStoryBase.Content;
                        }
                        if (xemlViewer.SelectedStoryBase.Content is StorySplit)
                        {
                            UnHideGroup(splitItems, true);
                            toolStripTextBoxStoryLabel.TextBox.DataBindings.Clear();
                            toolStripTextBoxStoryLabel.TextBox.DataBindings.Add("Text", xemlViewer.SelectedStoryBase.Content, "Label", true, DataSourceUpdateMode.OnPropertyChanged);
                            toolStripButtonStoryAnnotations.Tag = xemlViewer.SelectedStoryBase.Content;
                            _toolStripTimeBoxSplitTime.TimeSpanBox.DataBindings.Clear();
                            _toolStripTimeBoxSplitTime.TimeSpanBox.DataBindings.Add("Value", xemlViewer.SelectedStoryBase.Content, "TimePoint", true, DataSourceUpdateMode.OnPropertyChanged);
                            toolStripLabelTimeEditor.Text = (xemlViewer.SelectedStoryBase.Content as StorySplit).TimePoint.ToString();
                        }

                    }
                    if (e.SelectedStoryChanged)
                    {
                        this.parameterTreeCtrl1.SetupStory(xemlViewer.SelectedStoryBase.Content, this.parameterTreeCtrl1.FilterLevel);
                        if (xemlViewer.SelectedStoryBase.Content is Story)
                            this.germPlasmPoolsMgrCtrl1.Story = xemlViewer.SelectedStoryBase.Content as Story;
                        else
                        {
                            this.germPlasmPoolsMgrCtrl1.Story = xemlViewer.SelectedStoryBase.Root.Content as Story;
                        }

                        if (parameterTreeCtrl1.SelectedNode != null && parameterTreeCtrl1.SelectedNode.VariableSupervisor != null)
                            parameterEditCtrl1.NavigateTo(xemlViewer.SelectedStoryBase.Content, parameterTreeCtrl1.SelectedNode.VariableSupervisor, parameterTreeCtrl1.SelectedNode.VariableSupervisor.TermId);
                    }
                }
                else
                {
                    this.parameterTreeCtrl1.SetupStory(null, this.parameterTreeCtrl1.FilterLevel);
                    this.germPlasmPoolsMgrCtrl1.Story = null;
                }
            }

            if (e.SelectedObservationPointChanged && e.MostTopSelectedElement == Xeml.Visualization.VisualDocElement.ObservationPoint)
            {
                if (xemlViewer.SelectedObservationPoint != null)
                {
                    UnHideGroup(obPointItems, true);
                    _toolStripTimeBoxObPoint.TimeSpanBox.DataBindings.Clear();
                    _toolStripTimeBoxObPoint.TimeSpanBox.DataBindings.Add("Value", xemlViewer.SelectedObservationPoint, "TimePoint", true, DataSourceUpdateMode.OnPropertyChanged);
                    toolStripLabelTimeEditor.Text = xemlViewer.SelectedObservationPoint.TimePoint.ToString();
                }
            }

            if (e.SelectedEventChanged && e.MostTopSelectedElement == Xeml.Visualization.VisualDocElement.Event)
            {
                if (xemlViewer.SelectedEvent != null)
                {
                    // xemlObjectDetailsCtrl.SetObject(xemlViewer.SelectedEvent);
                    UnHideGroup(eventItems, true);
                    _toolStripTimeBoxEvent.TimeSpanBox.DataBindings.Clear();
                    _toolStripTimeBoxEvent.TimeSpanBox.DataBindings.Add("Value", xemlViewer.SelectedEvent, "TimePoint", true, DataSourceUpdateMode.OnPropertyChanged);
                    toolStripTextBoxEventLabel.TextBox.DataBindings.Clear();
                    toolStripTextBoxEventLabel.TextBox.DataBindings.Add("Text", xemlViewer.SelectedEvent, "Label", true, DataSourceUpdateMode.OnPropertyChanged);
                    toolStripLabelTimeEditor.Text = xemlViewer.SelectedEvent.TimePoint.ToString();
                }
            }

            if (e.MostTopSelectedElement == Xeml.Visualization.VisualDocElement.None)
            {
                UnHideGroup(expItems, true);

            }

            toolStripDetails.ResumeLayout();
        }



        //void XemlViewer_StorySelected(object sender, EventArgs e)
        //{



        //}

        //void XemlViewer_ExperimentSelected(object sender, EventArgs e)
        //{
        //    //this.germPlasmPoolsMgrCtrl1.Story = null;
        //    //this.parameterStackView.Story = null;
        //    //this.parameterTreeCtrl1.SetupStory(null, this.parameterTreeCtrl1.FilterLevel);
        //    //xemlObjectDetailsCtrl.SetObject(fMgr.CurrentXemlDoc);
        //}

        //void XemlViewer_ObservationPointSelected(object sender, EventArgs e)
        //{

        //}

        //void XemlViewer_EventSelected(object sender, EventArgs e)
        //{

        //}

        #region FileManager events
        void fMgr_LogChanged(object sender, EventArgs e)
        {
            kryptonCheckButtonInfos.Text = fMgr.LogInfoCount + " Infos";
            kryptonCheckButtonWarnings.Text = fMgr.LogWarningCount + " Warnings";
            kryptonCheckButtonError.Text = fMgr.LogErrorCount + " Errors";
        }

        void fMgr_DesignModeRejected(object sender, EventArgs e)
        {
            kryptonSplitContainerDesignParams.Enabled = false;
            documentResourceCtrl.Enabled = false;
            //xemlObjectDetailsCtrl.Enabled = false;
            //advancedXemlViewer.Enabled = false;
            //parameterStackView.Enabled = false;
            //documentResourceCtrl.Enabled = false;
            MessageBox.Show("The current document is invalid. The design view has been disabled. Please check the xeml code and the error log.", "Document error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //void fMgr_EditModeChanged(object sender, EventArgs e)
        //{
        //    if (fMgr.EditMode == EditMode.CodeMode)
        //    {
        //        toolStripStatusLabelEditMode.Text = "CodeMode";

        //    }
        //    else
        //    {
        //        toolStripStatusLabelEditMode.Text = "DesignMode";
        //        //advancedXemlViewer.Enabled = true;
        //        //parameterStackView.Enabled = true;
        //        //documentResourceCtrl.Enabled = true;
        //        kryptonSplitContainerDesignParams.Enabled = true;
        //        documentResourceCtrl.Enabled = true;
        //        kryptonPageResources.Enabled = true;
        //    }
        //}

        void fMgr_FilePathNeeded(object sender, FilePathNeededEventArgs e)
        {
            saveFileDialogDocument.FileName = e.Path;
            if (saveFileDialogDocument.ShowDialog() == DialogResult.OK)
            {
                e.Path = saveFileDialogDocument.FileName;
            }
            else
            {
                e.Cancel = true;
            }
        }

        void fMgr_FileSaved(object sender, EventArgs e)
        {
            this.Text = this.Text.Replace(" (unsaved)", "");
        }

        void fMgr_SomethingChanged(object sender, EventArgs e)
        {
            this.Text = this.Text + " (unsaved)";
        }

        void fMgr_FilePathChanged(object sender, EventArgs e)
        {
            toolStripStatusLabelFilePath.Text = fMgr.FilePath;
        }

        void OnDocumentLoaded(object sender, EventArgs e)
        {
            //this.Text = this.Text.Replace("(unsaved)", "");
            //syntaxDocumentXeml.Change -= new EventHandler(syntaxDocumentXeml_Change);
            this.xemlViewer.XemlDoc = fMgr.CurrentXemlDoc;

            if (!fMgr.InvalidDocument)
            {
                this.xemlViewer.Enabled = true;
                this.headerEdtCtrl1.Setup(fMgr.CurrentXemlDoc);
                this.htmlReportCtrl1.Setup(fMgr.CurrentXemlDoc);
                //this.parameterStackView.Enabled = true;
                //   this.syntaxDocumentXeml.Text = fMgr.CurrentXemlDoc.Xeml;
                //this.parameterStackView.ParamResources = fMgr.CurrentXemlDoc.DocumentRessources.EnvironmentOntologyHandler;
                this.parameterTreeCtrl1.Setup(fMgr.CurrentXemlDoc.DocumentResources, 2);
                this.parameterTreeCtrl1.SetupStory(xemlViewer.SelectedStoryBase.Content, this.parameterTreeCtrl1.FilterLevel);
                //this.sef.Setup(fMgr.CurrentXemlDoc.DocumentResources.EnvironmentOntologyHandler, fMgr.CurrentXemlDoc.ObservationTime - TimeSpan.FromSeconds(1), 2);
                this.documentResourceCtrl.XemlDoc = fMgr.CurrentXemlDoc;

                toolStripTextBoxExpName.TextBox.DataBindings.Clear();
                toolStripTextBoxExpName.TextBox.DataBindings.Add("Text", fMgr.CurrentXemlDoc, "Name", true, DataSourceUpdateMode.OnPropertyChanged);
                toolStripTextBoxExpName.TextBox.DataBindings[0].ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;

                _toolStripDateTimePickerStartTime.DateTimePicker.DataBindings.Clear();
                _toolStripDateTimePickerStartTime.DateTimePicker.DataBindings.Add("Value", fMgr.CurrentXemlDoc, "StartDate", true, DataSourceUpdateMode.OnPropertyChanged);
                _toolStripDateTimePickerStartTime.DateTimePicker.DataBindings[0].ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;

                _toolStripTimeBoxObservationLength.TimeSpanBox.DataBindings.Clear();
                _toolStripTimeBoxObservationLength.TimeSpanBox.DataBindings.Add("Value", fMgr.CurrentXemlDoc, "ObservationTime", true, DataSourceUpdateMode.OnPropertyChanged);
                _toolStripTimeBoxObservationLength.TimeSpanBox.DataBindings[0].ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;


                if (kryptonNavigatorMain.SelectedPage == kryptonPageTableLayout)
                    tableFormatterCtrl1.Format(fMgr.CurrentXemlDoc);
                if (kryptonNavigatorMain.SelectedPage == kryptonPageHtml)
                    htmlReportCtrl1.Setup(fMgr.CurrentXemlDoc);
            }
            else
            {
                this.xemlViewer.Enabled = false;
                this.headerEdtCtrl1.Setup(null);
                this.htmlReportCtrl1.Setup(null);
                //this.parameterStackView.Enabled = false;
                // this.syntaxDocumentXeml.Text = fMgr.SourceCodeCache;

                //MessageBox.Show("File is invalid!! Designer is disabled!");
            }
            //syntaxDocumentXeml.Change += new EventHandler(syntaxDocumentXeml_Change);
            // xemlObjectDetailsCtrl.SetObject(fMgr.CurrentXemlDoc);


        }

        void OnNewFile(object sender, EventArgs e)
        {
            if (fMgr.CurrentXemlDoc.Id == Guid.Empty)
            {
                createNewDocumentIDToolStripMenuItem_Click(sender, e);
            }
        }
        #endregion

        #region Command events

        /// <summary>
        /// Loads a document.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoadDocument(object sender, EventArgs e)
        {
            if (CheckUnsavedChanges())
            {
                if (openFileDialogDocument.ShowDialog() == DialogResult.OK)
                {

                    fMgr.LoadFile(openFileDialogDocument.FileName, false);
                }
            }
        }

        private void OnNewFromTemplate(object sender, EventArgs e)
        {
            if (CheckUnsavedChanges())
            {
                NewFromTemplateFrm nftf = new NewFromTemplateFrm();
                if (nftf.ShowDialog() == DialogResult.OK)
                {
                    fMgr.LoadFile(nftf.FileName, true);
                }
                //if (openFileDialogDocument.ShowDialog() == DialogResult.OK)
                //{

                //    fMgr.LoadDocument(openFileDialogDocument.FileName, true);
                //}
            }

        }

        /// <summary>
        /// Creates a new document.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNewDocument(object sender, EventArgs e)
        {
            if (CheckUnsavedChanges())
            {
                fMgr.New();
            }

        }

        /// <summary>
        /// Save the current document.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnSaveDocument(object sender, EventArgs e)
        {
            fMgr.SaveDocument();
        }

        /// <summary>
        /// Saves the document under a differnt name.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnSaveDoucumentAs(object sender, EventArgs e)
        {
            fMgr.SaveDocumentAs();
        }

        /// <summary>
        /// Exit the app.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnExit(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Navigating through the differnt views.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnViewNavigation(object sender, EventArgs e)
        {
            //if (kryptonNavigatorMain.SelectedPage == kryptonPageDesign || kryptonNavigatorMain.SelectedPage == kryptonPageResources)
            //{
            //    fMgr.SetDesignMode();
            //}
            //if (kryptonNavigatorMain.SelectedPage == kryptonPageXeml)
            //{
            //    if (fMgr.EditMode == EditMode.DesignMode)
            //    {
            //        syntaxDocumentXeml.Change -= new EventHandler(syntaxDocumentXeml_Change);
            //        fMgr.CurrentXemlDoc.RefreshXeml();
            //        syntaxDocumentXeml.Text = fMgr.CurrentXemlDoc.Xeml;
            //        syntaxDocumentXeml.Change += new EventHandler(syntaxDocumentXeml_Change);
            //    }
            //}
            if (kryptonNavigatorMain.SelectedPage == kryptonPageTableLayout)
            {
                //_tableFormatterWorker.RunWorkerAsync();
                tableFormatterCtrl1.Format(fMgr.CurrentXemlDoc);
            }
            if (kryptonNavigatorMain.SelectedPage == kryptonPageValidation)
            {
                fMgr.DoValidation(true);
            }

            if (kryptonNavigatorMain.SelectedPage == kryptonPageHtml)
            {
                htmlReportCtrl1.GenerateReport();
            }
        }

        /// <summary>
        /// Changes the filter settings for the validation log
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLogFilterChange(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            if (!kryptonCheckButtonError.Checked)
            {
                sb.Append("SeverityCode <> 'Error'");
            }
            if (!kryptonCheckButtonWarnings.Checked)
            {
                if (sb.Length > 0)
                    sb.Append(" and ");
                sb.Append("SeverityCode <> 'Warning'");
            }
            if (!kryptonCheckButtonInfos.Checked)
            {
                if (sb.Length > 0)
                    sb.Append(" and ");
                sb.Append("SeverityCode <> 'Info'");
            }
            validationLogBindingSource.Filter = sb.ToString();
        }

        /// <summary>
        /// Handling for source code change.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //void syntaxDocumentXeml_Change(object sender, EventArgs e)
        //{
        //    fMgr.SetXemlCode(syntaxDocumentXeml.Text, true, true);
        //}

        /// <summary>
        /// The application is closing
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(CancelEventArgs e)
        {
            e.Cancel = !CheckUnsavedChanges();
            base.OnClosing(e);
        }

        /// <summary>
        /// Cuts the current element.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCut(object sender, EventArgs e)
        {
            //if (kryptonNavigatorMain.SelectedPage == kryptonPageXeml)
            //{
            //    this.codeEditorControl.Cut();
            //}
        }

        /// <summary>
        /// Copy the current element to the clipboard.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCopy(object sender, EventArgs e)
        {
            //if (kryptonNavigatorMain.SelectedPage == kryptonPageXeml)
            //{
            //    this.codeEditorControl.Copy();
            //}
            if (kryptonNavigatorMain.SelectedPage == kryptonPageTableLayout)
            {
                this.tableFormatterCtrl1.CopyToClipBoard();
            }
        }

        /// <summary>
        /// Paste the content from the clipboard.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPaste(object sender, EventArgs e)
        {
            //if (kryptonNavigatorMain.SelectedPage == kryptonPageXeml)
            //{
            //    this.codeEditorControl.Paste();
            //}
        }

        /// <summary>
        /// Undo last action.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnUndo(object sender, EventArgs e)
        {

            fMgr.Undo();
            //if (kryptonNavigatorMain.SelectedPage == kryptonPageXeml)
            //{
            //    this.codeEditorControl.Undo();
            //}
        }

        /// <summary>
        /// Redo last action.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnRedo(object sender, EventArgs e)
        {
            fMgr.Redo();
            //if (kryptonNavigatorMain.SelectedPage == kryptonPageXeml)
            //{
            //    this.codeEditorControl.Redo();
            //}
        }

        /// <summary>
        /// Shows the about box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnShowAboutDialog(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }
        #endregion

        #region Layouting


        void CollapseParameterContainer(object sender, EventArgs e)
        {
            // Suspend layout changes until all splitter properties have been updated
            kryptonSplitContainerDesignParams.SuspendLayout();

            // Is the bottom right header group currently expanded?
            if (kryptonSplitContainerDesignParams.FixedPanel == FixedPanel.None)
            {
                // Make the bottom panel of the splitter fixed in size
                kryptonSplitContainerDesignParams.FixedPanel = FixedPanel.Panel1;
                kryptonSplitContainerDesignParams.IsSplitterFixed = true;

                // Remember the current height of the header group (to restore later)
                lastParameterContainerWidth = kryptonHeaderGroupParameter.Width;

                // Find the new height to use for the header group
                int newHeight = kryptonHeaderGroupParameter.PreferredSize.Width;

                // Make the header group fixed to the new height
                kryptonSplitContainerDesignParams.Panel1MinSize = newHeight;
                kryptonSplitContainerDesignParams.SplitterDistance = newHeight;//kryptonSplitContainerDesignParams.PreferredSize.Width;
            }
            else
            {
                // Make the bottom panel not-fixed in size anymore
                kryptonSplitContainerDesignParams.FixedPanel = FixedPanel.None;
                kryptonSplitContainerDesignParams.IsSplitterFixed = false;

                // Put back the minimise size to the original
                kryptonSplitContainerDesignParams.Panel1MinSize = 100;

                // Calculate the correct splitter we want to put back
                kryptonSplitContainerDesignParams.SplitterDistance = lastParameterContainerWidth;// kryptonSplitContainerDesignParams.Width - lastParameterContainerWidth - kryptonSplitContainerDesignParams.SplitterWidth;
            }

            kryptonSplitContainerDesignParams.ResumeLayout();
        }

        //void CollapsDetailContainer(object sender, EventArgs e)
        //{
        //    // Suspend layout changes until all splitter properties have been updated
        //    kryptonSplitContainerDetails.SuspendLayout();

        //    // Is the bottom right header group currently expanded?
        //    if (kryptonSplitContainerDetails.FixedPanel == FixedPanel.None)
        //    {
        //        // Make the bottom panel of the splitter fixed in size
        //        kryptonSplitContainerDetails.FixedPanel = FixedPanel.Panel2;
        //        kryptonSplitContainerDetails.IsSplitterFixed = true;

        //        // Remember the current height of the header group (to restore later)
        //        lastDetailContainerHeight = kryptonHeaderGroupDetails.Height;

        //        // Find the new height to use for the header group
        //        int newHeight = kryptonHeaderGroupDetails.PreferredSize.Height;

        //        // Make the header group fixed to the new height
        //        kryptonSplitContainerDetails.Panel2MinSize = newHeight;
        //        kryptonSplitContainerDetails.SplitterDistance = kryptonSplitContainerDetails.Height;
        //    }
        //    else
        //    {
        //        // Make the bottom panel not-fixed in size anymore
        //        kryptonSplitContainerDetails.FixedPanel = FixedPanel.None;
        //        kryptonSplitContainerDetails.IsSplitterFixed = false;

        //        // Put back the minimise size to the original
        //        kryptonSplitContainerDetails.Panel2MinSize = 100;

        //        // Calculate the correct splitter we want to put back
        //        kryptonSplitContainerDetails.SplitterDistance = kryptonSplitContainerDetails.Height - lastDetailContainerHeight - kryptonSplitContainerDetails.SplitterWidth;
        //    }

        //    kryptonSplitContainerDetails.ResumeLayout();
        //}

        /// <summary>
        /// Formats the validation log datagridview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewLog_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex % 2 == 0)
            {
                e.CellStyle.BackColor = Color.White;
                e.CellStyle.SelectionBackColor = Color.White;
                e.CellStyle.SelectionForeColor = Color.Black;
            }
            else
            {
                e.CellStyle.BackColor = Color.Cornsilk;
                e.CellStyle.SelectionBackColor = Color.Cornsilk;
                e.CellStyle.SelectionForeColor = Color.Black;
            }

            if (e.ColumnIndex == 0)
            {
                e.CellStyle.BackColor = Color.White;
                e.CellStyle.SelectionBackColor = Color.White;
                DataGridView dgv = sender as DataGridView;

                string sevcode = (dgv.Rows[e.RowIndex].Cells["severityCodeDataGridViewTextBoxColumn"].Value as string);
                switch (sevcode)
                {
                    case "Info":
                        {
                            dgv.Rows[e.RowIndex].Cells["icon"].Value = MainResources.InfoIcon;
                            break;
                        }
                    case "Warning":
                        {
                            dgv.Rows[e.RowIndex].Cells["icon"].Value = MainResources.WarningIcon;
                            break;
                        }
                    case "Error":
                        {
                            dgv.Rows[e.RowIndex].Cells["icon"].Value = MainResources.ErrorIcon;
                            break;
                        }
                }

            }

        }
        #endregion

        #region Helper methods
        //private void SetupSyntaxDoc()
        //{
        //    string tempPath = Path.GetTempPath();
        //    tempPath += "\\xml.syn";

        //    File.WriteAllBytes(tempPath, MainResources.XMLSyntax);
        //    syntaxDocumentXeml.SyntaxFile = tempPath;


        //}


        private bool CheckUnsavedChanges()
        {
            if (fMgr.UnsavedChanges)
            {
                DialogResult dr = MessageBox.Show("You have unsaved changes in the current document. Do you want save now?", "Save needed", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.Cancel)
                    return false;
                if (dr == DialogResult.Yes)
                    fMgr.SaveDocument();
            }
            return true;
        }
        #endregion



        //private void germPlasmEditorToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    GermPlasmEditForm gef = new GermPlasmEditForm(null);

        //    gef.Show();
        //    gef.Location = this.Location;
        //}

        private void OnEditGermPlasmPool(object sender, EventArgs e)
        {
            EditGermPlasmPool(null);
        }

        private void germPlasmPoolsMgrCtrl1_GermPlasmEdit(object sender, Xid.Controls.GermPlasmEditEventargs e)
        {
            EditGermPlasmPool(e.IndividualsPool);
        }

        private void EditGermPlasmPool(IndividualsPool ip)
        {
            bool addPool = ip == null;
            if (xemlViewer.SelectedStoryBase != null)
            {
                Story story = xemlViewer.SelectedStoryBase.Root.Content as Story;

                GermPlasmEditForm gef = new GermPlasmEditForm(ip);

                //gef.Location = this.Location;
                if (gef.ShowDialog(this) == DialogResult.OK)
                {
                    if (addPool)
                        story.Pools.Add(gef.IndividualsPool);
                }
            }
            else
                NoBaseStoryMsgBox();
        }

        /// <summary>
        /// Detect is in the current stories germplasm has been added. Mostly used to determine if we can already add samples.
        /// </summary>
        /// <returns>true on having germplasm</returns>
        private bool hasGermplasm()
        {
            foreach (TreeNode<StoryBase> stNode in xemlViewer.XemlDoc.StoryBoard.VirtualRoot.SubNodes(false))
            {
                if ((stNode.Content as Story).Pools.Count(x => !String.IsNullOrEmpty(x.GermPlasm)) > 0) // check if germplasm is filled in
                {
                    return true;
                }
            }
            return false;
        }

        private void toolStripButtonSampling_Click(object sender, EventArgs e)
        {
            //if (xemlViewer.SelectedStoryBase != null && xemlViewer.SelectedStoryBase.Content is Story)
            //{
            if (xemlViewer.SelectedObservationPoints.Length > 0)
            {
                bool cancel = false; // prevent the SamplingStrategyForm to pop up if set to true
                if (!hasGermplasm())
                {
                    DialogResult addGermplasm = MessageBox.Show("No germplasm was detected. Do you want to add one now?", "No germplasm detected!", MessageBoxButtons.YesNoCancel);
                    switch (addGermplasm)
                    {
                        case DialogResult.Yes: // take me to your genotype
                            EditGermPlasmPool(null);
                            break;
                        case DialogResult.Cancel: // HANNA'S ESCAPE ABORT ABORT!
                            cancel = true;
                            break;
                        case DialogResult.No: // just show the normal dialog, e.g. do nothing :)
                        default:
                            break;
                    }
                }
                if (!cancel)
                {
                    SamplingStrategyForm ssf = new SamplingStrategyForm(fMgr.CurrentXemlDoc);
                    if (ssf.ShowDialog(this) == DialogResult.OK)
                    {
                        AddSamples(ssf.Templates);
                    }
                }
            }
            else
                MessageBox.Show("No observation points selected", "No ObservationPoints", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
            //else
            //    NoBaseStoryMsgBox();
        }


        private void AddSamples(List<SampleTemplate> templates)
        {
            Random r = new Random(42);
            foreach (ObservationPoint obPoint in xemlViewer.SelectedObservationPoints)
            {

                StoryBase sb = obPoint.Collection.Story;
                foreach (SampleTemplate st in templates)
                {
                    TreeNode<StoryBase> obPointStoryRoot = fMgr.CurrentXemlDoc.StoryBoard.FindNode(obPoint.Collection.Story).Root;
                    // (obPointStoryRoot.Content as Story).Pools.Contains(st.IndividualsPool)
                    // StoryBase templateObservationStory = st.Observation.IndividualsPool.Collection.Owner as StoryBase;
                    if ((obPointStoryRoot.Content as Story).Pools.Contains(st.IndividualsPool))
                    {
                        IndividualsPool ip = (obPointStoryRoot.Content as Story).Pools.Find(st.IndividualsPool);
                        for (int j = 0; j < st.ReplicaCount; j++)
                        {
                            Dictionary<int, List<Partition>> samples = new Dictionary<int, List<Partition>>();
                            for (int i = 1; i <= st.ObservationCount; i++)
                            {
                                Observation o = new Observation(st.Observation);
                                Individual ind = new Individual();
                                ind.Id = IndividualIndexer.Instance.NextId(true);

                                //while (o.IndividualsPool.Individuals.Contains(ind.Id))
                                //    ind.Id = r.Next();
                                o.IndividualsPool = ip;
                                o.IndividualsPool.Individuals.Add(ind);
                                o.Individual = ind;
                                obPoint.Observations.Add(o);
                                int partIndx = 0;
                                foreach (Partition p in o.Partitions)
                                {
                                    p.Id = PartitionIndexer.Instance.NextId(sb);
                                    if (!samples.ContainsKey(partIndx))
                                        samples.Add(partIndx, new List<Partition>());
                                    samples[partIndx].Add(p);
                                    partIndx++;
                                }
                            }

                            foreach (int partIndx in samples.Keys)
                            {
                                Sample s = new Sample();
                                s.Id = SampleIndexer.Instance.NextId();
                                s.TimeIntermix = TimeIntermix.Min;
                                s.AddPartitionRange(samples[partIndx]);
                                //foreach (Partition p in samples[partIndx])
                                //{
                                //    s.AddPartition(p);
                                //}
                                sb.Samples.Add(s);
                            }

                        }
                    }
                }
            }

            SampleIndexer.Instance.NormalizeIndex();

        }


        private void NoStoryMsgBox()
        {
            MessageBox.Show("No story selected!", "No story", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void NoBaseStoryMsgBox()
        {
            MessageBox.Show("No base story selected!", "No base story", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void observationLayoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ObservationLayoutEditFrm f = new ObservationLayoutEditFrm();
            f.ObservationPoint = this.xemlViewer.SelectedObservationPoint;
            f.Show(this);
        }



        private void normalizeSampleIndxToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SampleIndexer.Instance.NormalizeIndex();
        }

        private void clearAllSamplingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("You about to delete all sampling data. Do you want to proceed?", "Reset sampling", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
                DocumentHelper.ClearAllSampling(fMgr.CurrentXemlDoc);
        }

        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.xemlViewer.SelectedStoryBase != null)
                sef.NavigateTo(this.xemlViewer.SelectedStoryBase.Content, this.parameterTreeCtrl1.FilterLevel);
            else
                sef.NavigateTo(null, this.parameterTreeCtrl1.FilterLevel);
            sef.ShowDialog(this);
        }

        private void parameterBrowserCtrl1_ParmaterNavigationRequested(object sender, Xid.Controls.ParameterBrowserCtrls.ParameterNavEventArgs e)
        {
            sef.NavigateTo(this.xemlViewer.SelectedStoryBase.Content, e.Target, parameterTreeCtrl1.FilterLevel);
            sef.ShowDialog();
        }

        private void annotateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (this.xemlViewer.MostTopSelectedElement)
            {
                case Xeml.Visualization.VisualDocElement.None:
                    break;
                case Xeml.Visualization.VisualDocElement.ObservationPoint:
                    {
                        af.Setup(this.xemlViewer.SelectedObservationPoint);
                        af.ShowDialog(this);
                        break;
                    }
                case Xeml.Visualization.VisualDocElement.Event:
                    {
                        af.Setup(this.xemlViewer.SelectedEvent);
                        af.ShowDialog(this);
                        break;
                    }
                case Xeml.Visualization.VisualDocElement.SplitDot:
                    {
                        goto case Xeml.Visualization.VisualDocElement.Story;

                    }
                case Xeml.Visualization.VisualDocElement.Story:
                    {
                        af.Setup(this.xemlViewer.SelectedStoryBase.Content);
                        af.ShowDialog(this);
                        break;
                    }
                case Xeml.Visualization.VisualDocElement.SwitchPoint:
                    break;
                default:
                    break;
            }



        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsFrm s = new SettingsFrm();
            if (s.ShowDialog() == DialogResult.OK)
            {
                ApplyStyle();
                fMgr.InitDirectories();
            }
        }

        private void ApplyStyle()
        {
            switch (Properties.Settings.Default.Style)
            {
                case "SparkleBlue":
                    {
                        kryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleBlue;
                        this.xemlViewer.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.BlueMetal;
                        //this.xemlObjectDetailsCtrl.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        break;
                    }
                case "SparkleOrange":
                    {
                        kryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleOrange;
                        this.xemlViewer.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.BlueMetal;
                        //this.xemlObjectDetailsCtrl.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        break;
                    }
                case "SparklePurple":
                    {
                        kryptonManager.GlobalPaletteMode = PaletteModeManager.SparkleOrange;
                        this.xemlViewer.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.BlueMetal;
                        //this.xemlObjectDetailsCtrl.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        break;
                    }
                case "Office2007Black":
                    {
                        kryptonManager.GlobalPalette = kryptonPaletteOfficeBlack;
                        this.xemlViewer.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        //this.xemlObjectDetailsCtrl.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        break;
                    }
                case "Office2007Silver":
                    {
                        kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Silver;
                        this.xemlViewer.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        //this.xemlObjectDetailsCtrl.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        break;
                    }
                case "Office2007Blue":
                    {
                        kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Blue;
                        this.xemlViewer.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.BlueMetal;
                        //this.xemlObjectDetailsCtrl.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.BlueMetal;
                        break;
                    }
                case "System":
                    {
                        kryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalSystem;
                        this.xemlViewer.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        //this.xemlObjectDetailsCtrl.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        break;
                    }
                case "Office2003":
                    {
                        kryptonManager.GlobalPaletteMode = PaletteModeManager.ProfessionalSystem;
                        this.xemlViewer.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        //this.xemlObjectDetailsCtrl.DrawAreaStyle = Xeml.Visualization.Controls.DrawAreaStyle.SilverMetal;
                        break;
                    }
                default:
                    break;
            }
            kryptonManager.GlobalAllowFormChrome = Properties.Settings.Default.AllowFormChrome;

        }





        private SourcecodeForm sourceCodeForm = new SourcecodeForm();
        private void codeEditorToolStripMenuItem_Click(object sender, EventArgs e)
        {

            fMgr.CurrentXemlDoc.RefreshXeml();
            sourceCodeForm.SourceCode = fMgr.CurrentXemlDoc.Xeml;
            if (sourceCodeForm.ShowDialog(this) == DialogResult.OK)
            {
                fMgr.SetXemlCode(sourceCodeForm.SourceCode, true, true);
            }
        }

        private void OnViewSamplingInfo(object sender, EventArgs e)
        {
            ObservationLayoutEditFrm olef = new ObservationLayoutEditFrm();
            olef.ObservationPoint = xemlViewer.SelectedObservationPoint;
            olef.ShowDialog();
        }

        private void OnDeleteSamples(object sender, EventArgs e)
        {
            if (MessageBox.Show("You about to delete sampling data for the current selected ObservationPoint. Do you want proceed?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                DocumentHelper.ClearRelatedSampling(this.xemlViewer.SelectedObservationPoint);
            }
        }

        private void gettingStartedToolStripMenuItem_Click(object sender, EventArgs e)
        {
#if OFFLINE
            if (MessageBox.Show("This function will contact our webserver at xeml.mpimp-golm.mpg.de. Do you want proceed?", "Online contact", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                == DialogResult.No)
                return;
#endif
            Process.Start(@"http://xeml.mpimp-golm.mpg.de/DNN/LinkClick.aspx?fileticket=LUZlXjAb7Lw%3d&tabid=56&mid=380&forcedownload=true");
        }

        private void jahu()
        {
            //fMgr.LoadFile(@"P:\AFE_FOR_GMD ANOTATED DATA\XEMLStore\13041gf anja thalhammer.xeml", false);

            Guid xemlId = Guid.Parse("061DBDEB-F3DD-4AFA-ACFD-54E83479C3DD");
            fMgr.LoadXeml(Xid.Controls.XemlStore.LoadFromXemlStoreFrm.LoadXemlFromStore(xemlId, Properties.Settings.Default.XemlStoreConnectionString), false);
            //dataMappingToolStripMenuItem.PerformClick();
        }

        private void dataMappingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DataProviderResource dataProvider = GetADataProvider();
                if (dataProvider != null)
                {
                    Xid.Controls.SampleCompiler.DataMappingFrm MappingForm = new Xid.Controls.SampleCompiler.DataMappingFrm(this.xemlViewer.XemlDoc as XemlDocument, dataProvider);
                    xemlViewer.ObservationPointSelected += new EventHandler<ObservationPointSelectedEventArgs>(MappingForm.SelectedSampleChanged);
                    MappingForm.Show(this);
                }
            }
            catch (OperationCanceledException ocex) { }
            catch (Exception ex)
            {
                Microsoft.SqlServer.MessageBox.ExceptionMessageBox box = new Microsoft.SqlServer.MessageBox.ExceptionMessageBox(ex);
                box.Show(this);
            }
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CheckUnsavedChanges())
            {
                try
                {
                    Xid.Controls.XemlStore.LoadFromXemlStoreFrm frmOpen = new Xid.Controls.XemlStore.LoadFromXemlStoreFrm(Properties.Settings.Default.XemlStoreConnectionString);
                    if (frmOpen.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        fMgr.LoadXeml(frmOpen.SelectedXeml, false);
                    }
                }
                catch (Exception ex)
                {
                    Microsoft.SqlServer.MessageBox.ExceptionMessageBox box = new Microsoft.SqlServer.MessageBox.ExceptionMessageBox(ex);
                    box.Show(this);
                }
            }
        }

        private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                IDataProvider dataProvider = GetADataProvider().Provider;
                if (dataProvider != null)
                {
                    if (MessageBox.Show(String.Concat("Saving to ", dataProvider.ComponentName, ". Continue?"), "Are you sure?", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    {
                        if (XemlDataSet.Save(fMgr.CurrentXemlDoc as XemlDocument, dataProvider, FeedbackUpdateDocument))
                        {
                            MessageBox.Show("Document saved/updated in Xeml Store");
                        }
                        else
                        {
                            MessageBox.Show("Document not saved/updated in Xeml Store");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Document not saved (due to missing DataProviderResource)");
                }
            }
            catch (OperationCanceledException ocex) { }
            catch (Exception ex)
            {
                Microsoft.SqlServer.MessageBox.ExceptionMessageBox box = new Microsoft.SqlServer.MessageBox.ExceptionMessageBox(ex);
                box.Show(this);
            }
        }

        private bool FeedbackUpdateDocument(string name, Guid XemlId)
        {
            return MessageBox.Show(this, string.Format("The document with title '{0}' and id '{1}' is allready present in the data base. Do you want to update the current version?", name, XemlId), "document allready present in XEML store", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes;
        }

        private void purgeDetailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you really sure you want to delete all the details from the current XEML document?", "Purge meta data?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2, MessageBoxOptions.DefaultDesktopOnly) == System.Windows.Forms.DialogResult.Yes)
            {
                if (CheckUnsavedChanges())
                {
                    try
                    {
                        fMgr.PurgeDetailsFromDocument();
                    }
                    catch (Exception ex)
                    {
                        Microsoft.SqlServer.MessageBox.ExceptionMessageBox box = new Microsoft.SqlServer.MessageBox.ExceptionMessageBox(ex);
                        box.Show(this);
                    }
                }
            }
        }

        private void createNewDocumentIDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                (fMgr.CurrentXemlDoc as XemlDocument).NewId();
                MessageBox.Show(string.Concat("New document ID '", (fMgr.CurrentXemlDoc as XemlDocument).Id, "' cretaed."), "New document ID created", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                Microsoft.SqlServer.MessageBox.ExceptionMessageBox box = new Microsoft.SqlServer.MessageBox.ExceptionMessageBox(ex);
                box.Show(this);
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            MemoryTicker.Enabled = false;
            MemoryTicker.Stop();

            foreach (TraceListener item in Debug.Listeners)
            {
                item.Flush();
            }
        }

        private DataProviderResource GetADataProvider()
        {
            if (fMgr.CurrentXemlDoc.DocumentResources.DataProvider.Count > 1)
            {
                DataProviderSelectorForm dataProviderSelectorForm = new DataProviderSelectorForm(fMgr.CurrentXemlDoc);
                if (dataProviderSelectorForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    return dataProviderSelectorForm.SelectedDataProvider;
                }
                else
                {
                    throw new OperationCanceledException();
                }
            }

            if (fMgr.CurrentXemlDoc.DocumentResources.DataProvider.Count == 0)
            {
                if (MessageBox.Show("Please add a data provider first!", "Data provider missing", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    using (DataConnectionWizard dcwiz = new DataConnectionWizard())
                    {
                        dcwiz.ShowDialog(this.ParentForm);
                        if (dcwiz.ProviderResource != null)
                        {
                            this.xemlViewer.XemlDoc.DocumentResources.DataProvider.Add(dcwiz.ProviderResource);
                        }
                        else
                        {
                            throw new OperationCanceledException();
                        }
                    }
                }
                else
                {
                    throw new OperationCanceledException();
                }
            }

            return fMgr.CurrentXemlDoc.DocumentResources.DataProvider.FirstOrDefault();
        }

        internal void OnMessageEmitted(object sender, MessageEventArgs e)
        {
            if (statusStripMain.InvokeRequired)
            {
                statusStripMain.BeginInvoke(new Action<Object, MessageEventArgs>(OnMessageEmitted), sender, e);
            }
            else
            {
                try
                {
                    toolStripStatusLabelMessage.Text = String.Concat(
                        //DateTime.Now.ToString("yyyyMMddHHmmssffff"),
                        sender.ToString().Split('.').Last(), // get the classname of the invoker
                        ": ",
                        e.message
                    );
                    statusStripMain.Refresh();
                }
                catch (Exception) { }
            }
        }

        private void iSAExportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (Xid.Controls.IsaExport.frmIsaExport f = new Xid.Controls.IsaExport.frmIsaExport(fMgr.CurrentXemlDoc))
                {
                    f.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                Microsoft.SqlServer.MessageBox.ExceptionMessageBox box = new Microsoft.SqlServer.MessageBox.ExceptionMessageBox(ex);
                box.Show(this);
            }
        }
    }
}
